
package cn.edu.tsinghua.hpc.gsmtest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.ToggleButton;
import cn.edu.tsinghua.hpc.gsmtest.service.MessageReportHandlerService;
import cn.edu.tsinghua.hpc.gsmtest.utils.RILUtils;

public class MsgTester extends Activity {

    static private String TAG = "msgTester";

    static final int MENU_PREFERENCES = 0;

    private List<Map<String, Object>> mData;

    private ListView mListView = null;

    private ToggleButton mRunButton;

    private static final String INDEX = "index";

    private static final String VALUE = "value";

    // for statistics
    private int messageSentCount = 0;

    private int messageSentOKCount = 0;

    private boolean isLastSentOK = false;

    private void incMessageSentCount() {

        messageSentCount++;
    }

    private static final String[][] formats = {
            {
                    "40", "C0"
            }, {
                    "40", "F7"
            }, {
                    "40", "08"
            }, {
                    "40", "00"
            }, {
                    "00", "C0"
            }, {
                    "7F", "F6"
            },
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mListView = new ListView(this);
        mData = new ArrayList<Map<String, Object>>();
        init();
    }

    private void init() {
        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.msg_button_item, null);
        mListView.addFooterView(layout);
        mRunButton = (ToggleButton) layout.findViewById(R.id.msg_test_button);
        mRunButton.setOnCheckedChangeListener(mRunListener);
    }

    private class ReportHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            isLastSentOK = true;
            messageSentOKCount++;
            update();
            isLastSentOK = false;
        }
    }

    private Timer mTimer = new Timer();

    private ReportHandler mReportHandler = new ReportHandler();

    private class MessageTimerTask extends TimerTask {

        @Override
        public void run() {
            incMessageSentCount();
            if (messageSentCount <= Preferences.getIntById(R.string.pref_msg_times)) {

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        String address = Preferences.getStringById(R.string.pref_target_number);
                        int index = Preferences.getIntById(R.string.pref_msg_format);

                        RILUtils.sendMessage(address, formats[index][0], formats[index][1],
                                MsgTester.this);
                        update();

                    }
                });
            }else {
                this.cancel();
                mTimer.cancel();
            }
        }
    }

    private CompoundButton.OnCheckedChangeListener mRunListener = new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                messageSentCount = 0;
                messageSentOKCount = 0;
                isLastSentOK = false;
                GSMTesterActivity.messageService.setWaitMessageAddress(Preferences
                        .getStringById(R.string.pref_target_number), mReportHandler);
                mTimer = new Timer();

                mTimer.scheduleAtFixedRate(new MessageTimerTask(), 0, Preferences
                        .getIntById(R.string.pref_msg_internal) * 1000/* milliseconds */);
            } else {
                mTimer.cancel();
            }
        }

    };

    private void update() {
        mData.clear();
        mListView.clearTextFilter();

        addColumn(this.getString(R.string.msg_internal), Preferences
                .getStringById(R.string.pref_msg_internal));
        addColumn(this.getString(R.string.current_info), getInfo());
        addColumn(this.getString(R.string.msg_state), getState());
        addColumn(this.getString(R.string.statistic), getStat());
        addColumn(this.getString(R.string.target_number), Preferences
                .getStringById(R.string.pref_target_number));

        int index = Preferences.getIntById(R.string.pref_msg_format);
        addColumn(this.getString(R.string.msg_format), String.format("%d", index));
        if (Preferences.getBooleanById(R.string.pref_need_boot)) {
            if (isLastSentOK) {
                addColumn(this.getString(R.string.need_boot), this.getString(R.string.status_on));
            } else {
                addColumn(this.getString(R.string.need_boot), this.getString(R.string.status_off));
            }

        } else {
            addColumn(this.getString(R.string.need_boot), "");
        }

        SimpleAdapter adapter = new SimpleAdapter(this, mData, R.layout.msg_tester_item,
                new String[] {
                        INDEX, VALUE
                }, new int[] {
                        R.id.tag, R.id.value
                });
        mListView.setAdapter(adapter);
        setContentView(mListView);
    }

    private String getState() {
        // TODO Auto-generated method stub
        return "";
    }

    private String getInfo() {
        // TODO
        return "";
    }

    private String getStat() {
        return "" + messageSentCount + "/" + messageSentOKCount + "/"
                + Preferences.getStringById(R.string.pref_msg_times);
    }

    private void addColumn(String tag, Object value) {
        Map<String, Object> item;
        item = new HashMap<String, Object>();
        item.put(INDEX, tag);
        item.put(VALUE, value);
        mData.add(item);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        menu.add(0, MENU_PREFERENCES, 0, R.string.menu_preferences).setIcon(
                android.R.drawable.ic_menu_preferences);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case MENU_PREFERENCES:
                Intent intent = new Intent(this, Preferences.class);
                startActivity(intent);
                break;
            default:
                return false;
        }
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        update();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
